package ddz.core.dealer;

import com.kaka.util.IntArray;
import com.kaka.util.MathUtils;
import ddz.core.Cards;
import ddz.core.Pile;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 不洗牌算法
 */
public class NoShuffleDealer extends Dealer {

    public NoShuffleDealer(int several) {
        super(several);
    }

    @Override
    protected void shuffle() {
        cards.clear();
        init();
        Cards allCards = new Cards();
        for (Integer card : cards) {
            allCards.addCard(card);
        }
        cards.clear();
        int maxZha = MathUtils.random(2, 10);
        List<Pile> zhaList = new ArrayList<>(maxZha);
        for (int k = allCards.getMinValidIndex(); k < allCards.getMaxValidIndex(); k++) {
            if (zhaList.size() >= maxZha) break;
            boolean flag = MathUtils.randomBoolean();
            if (flag) {
                Pile pile = allCards.removePile(k);
                zhaList.add(pile);
            }
        }
        int[] _cards = allCards.getDesCards();
        for (int card : _cards) {
            cards.add(card);
        }
        Collections.shuffle(cards);
        IntArray cardsClone = new IntArray(cards.size());
        for (Integer card : cards) {
            cardsClone.add(card);
        }
        cards.clear();
        for (int m = 0; m < cardsClone.size(); m++) {
            int card = cardsClone.get(m);
            cards.add(card);
            boolean flag = MathUtils.randomBoolean();
            if (flag && cards.size() % 4 == 0 && !zhaList.isEmpty()) {
                Pile pile = zhaList.remove(zhaList.size() - 1);
                int[] pileCards = pile.getCards();
                for (int pileCard : pileCards) {
                    cards.add(pileCard);
                }
            }
        }
        while (!zhaList.isEmpty()) {
            Pile pile = zhaList.remove(zhaList.size() - 1);
            int[] pileCards = pile.getCards();
            for (int pileCard : pileCards) {
                cards.add(pileCard);
            }
        }
    }

    @Override
    public void distribute(Cards[] array, int remaing) {
        shuffle();
        distribute(array, remaing, 4);
    }

}
